package com.stars.aspect;

import com.stars.common.MyReflectionUtils;
import com.stars.common.MyStrRegex;
import com.stars.common.annotation.AutoCode;
import com.stars.common.annotation.AutoCodeClass;
import com.stars.common.valid.MyException;
import com.stars.services.sysdict.SysDictAccessServices;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.Table;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName DictAspect
 * @Description: 生成编号，按天，月
 * @Author DJ
 * @Date 2019/10/24
 * @Version V1.0
 **/
@Aspect
@Component
public class AutoCodeAspect {

    @Autowired
    private SysDictAccessServices sysDictAccessServicesImpl;

    @Pointcut("@annotation(autoCodeClass)")
    public void doDataDictClass(AutoCodeClass autoCodeClass) {
    }

    @Before("@annotation(autoCodeClass)")
    public void translation(JoinPoint point, AutoCodeClass autoCodeClass) throws Throwable {
        Object[] res = point.getArgs();
        if (res == null) {
            throw new MyException("参数错误");
        }
        Object obj = res[0];

        Table table = (Table) MyReflectionUtils.getDeclaredAnnotation(obj, Table.class);
        List<AutoCode> dictParams = boAutoCode(obj.getClass());
        if (dictParams.size() == 0) {
            return;
        }
        for (AutoCode dictParam : dictParams) {
            String whereVal = "";
            if(StringUtils.isNotBlank(dictParam.dbWhere())){
                String entityFieldName = MyStrRegex.underLineBackFirstCharToUpperCase(dictParam.dbWhere());
                Object fieldValue = MyReflectionUtils.getFieldValue(obj, entityFieldName);
                if(null != fieldValue){
                    whereVal = "'"+fieldValue.toString()+"'";
                }
            }
            String autoCode = sysDictAccessServicesImpl.createCode(table.name(), dictParam.dbCode(), dictParam.prefix(),dictParam.type(),dictParam.dbWhere(),whereVal);
            MyReflectionUtils.setFieldValue(obj, dictParam.valCode(), autoCode);
        }
    }

    /**
     * 获取bo中属性值
     *
     * @param cla
     * @return
     */
    private List<AutoCode> boAutoCode(Class cla) {
        Field[] fields = cla.getDeclaredFields();
        List<AutoCode> list = new ArrayList<>();
        for (Field field : fields) {
            if (field.isAnnotationPresent(AutoCode.class)) {
                AutoCode autoCode = field.getAnnotation(AutoCode.class);
                list.add(autoCode);
            }
        }
        return list;
    }


}
